/**
 * Copyright 2019 吉鼎科技.

 * <p>
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * <p>
 * http://www.apache.org/licenses/LICENSE-2.0
 * <p>
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package cn.easyplatform.web.task.support.scripting;

import cn.easyplatform.lang.Files;
import cn.easyplatform.type.FieldVo;
import cn.easyplatform.web.task.EventSupport;
import org.mozilla.javascript.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;

/**
 * @author <a href="mailto:davidchen@epclouds.com">littleDog</a> <br/>
 * @since 2.0.0 <br/>
 */
public class SimpleCompliableScriptEngine implements CompliableScriptEngine {

    private final static Logger log = LoggerFactory.getLogger(SimpleCompliableScriptEngine.class);

    private RhinoScriptable scope;

    private Script scriptEval;

    private SimpleCmd cmd;

    private static String functions;

    static {
        StringBuilder sb = new StringBuilder();
        //InputStream is = EventScriptEngine.class.getResourceAsStream("cmd0.so");
        sb.append(Files.read("support/lib/cmd0.so"));
        //is = EventScriptEngine.class.getResourceAsStream("cmd2.so");
        sb.append(Files.read("support/lib/cmd2.so"));
        functions = sb.toString();
        sb = null;
    }

    public SimpleCompliableScriptEngine(EventSupport handler) {
        Map<String, Object> map = new HashMap<String, Object>();
        scope = new RhinoScriptable(map, false);
        this.cmd = new SimpleCmd(handler, map);
    }

    @Override
    public void compile(String expr) {
        String[] exprs = ScriptUtils.parse(expr);
        if(log.isDebugEnabled())
        log.debug("eval expression:{}", expr);
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(9);
            scope.initStandardObjects(cx, false);
            StringBuilder sb = new StringBuilder();
            if (exprs.length > 1) {
                for (int i = 1; i < exprs.length; i++)
                    sb.append(exprs[i]).append("\n");
            }
            sb.append(functions).append("\n").append(exprs[0]);
            scope.setVariable("$", cmd);
            scriptEval = cx.compileString(sb.toString(), "", 1, null);
            sb = null;
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(ex);
        } finally {
            Context.exit();
        }
    }

    @Override
    public Object eval(Object... args) {
        if (args.length == 2) {
            if (args[0] instanceof FieldVo[])
                cmd.setSource((FieldVo[]) args[0]);
            if (args[1] instanceof FieldVo[])
                cmd.setTarget((FieldVo[]) args[1]);
        } else if (args.length == 1) {
            if (args[0] instanceof FieldVo[])
                cmd.setTarget((FieldVo[]) args[0]);
        }
        Context cx = Context.enter();
        try {
            cx.setOptimizationLevel(9);
            Object result = scriptEval.exec(cx, scope);
            if (result instanceof Wrapper)
                result = ((Wrapper) result).unwrap();
            return result instanceof Undefined ? null : result;
        } catch (RhinoException ex) {
            throw ScriptUtils.handleScriptException(ex);
        } finally {
            Context.exit();
        }
    }

    @Override
    public void destroy() {
        if (scope != null) {
            scope.clear();
            scope = null;
            scriptEval = null;
        }
    }
}
